package com.itheima.controller;

import com.itheima.pojo.User;
import com.itheima.service.UserService;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;

@WebServlet("/RegisterServlet")
public class RegisterServlet extends HttpServlet {

    private UserService userService = new UserService();

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        //0.先判断验证码是否正确，正确才执行后面的代码进行注册
        String checkCode = request.getParameter("checkCode");
        //获取服务器生成的验证码
        HttpSession session = request.getSession();
        String code = (String) session.getAttribute("code");
        //清除验证码
        session.removeAttribute("code");

        //这里不能使用重定向
        response.setContentType("text/html;charset=utf-8");
        PrintWriter out = response.getWriter();


        //比较验证码是否相等，忽略大小写比较
        if (!checkCode.equalsIgnoreCase(code)) {
            request.setAttribute("msg", "验证码错误");
            request.getRequestDispatcher("/register.jsp").forward(request, response);
            //注：一定要加上return，否则后面的代码还会执行
            return;
        }



        //1.获取用户的信息
        Map<String, String[]> parameterMap = request.getParameterMap();
        User user = new User();
        try {
            BeanUtils.populate(user, parameterMap);
        } catch (IllegalAccessException|InvocationTargetException e) {
            e.printStackTrace();
        }
        //2.调用业务层注册
        if (userService.register(user)) {
            //3.注册成功，跳转到登录页面
            //response.sendRedirect("login.jsp");
            out.print("<script>");
            out.print("alert('注册成功');");
            out.print("location.href='login.jsp';");
            out.print("</script>");
        }
        else {
            //4.注册失败，显示相应的信息
            request.setAttribute("msg", "注册失败，用户名已经存在");
            request.getRequestDispatcher("/register.jsp").forward(request, response);
        }
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}
